<template>
  <div class="product-management">
    <h1>我的商品管理</h1>
    <el-button @click="addItem">添加商品</el-button>
    <div v-if="isLoading">加载中...</div>
    <el-table v-else :data="items" stripe>
      <el-table-column prop="item_id" label="ID"></el-table-column>
      <el-table-column prop="product_name" label="商品名称"></el-table-column>
      <el-table-column prop="product_description" label="商品描述"></el-table-column>
      <el-table-column prop="product_price" label="商品价格"></el-table-column>
      <el-table-column prop="product_image" label="商品图片">
        <template #default="scope">
          <img :src="scope.row.product_image || 'https://via.placeholder.com/100?text=No+Image'" alt="商品图片" style="width: 50px;">
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="editItem(scope.row)">编辑</el-button>
          <el-button @click="confirmDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加商品弹窗 -->
    <el-dialog v-if="addDialogVisible" v-model="addDialogVisible" title="添加商品">
      <el-form :model="newItem" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="newItem.product_name"></el-input>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="newItem.product_description"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="newItem.product_price"></el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="upload-demo"
            action="#"
            :on-change="handleImageChange"
            :show-file-list="false"
            :before-upload="beforeUpload"
            ref="uploadRef"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <img v-if="newItem.product_image" :src="newItem.product_image" alt="商品图片" style="width: 100px; margin-top: 10px;">
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveItem">保存</el-button>
      </template>
    </el-dialog>
    <!-- 编辑商品弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑商品">
      <el-form :model="editedItem" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="editedItem.product_name" />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="editedItem.product_description" />
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input 
            v-model="editedItem.product_price" 
            type="number"
            step="0.01"
            placeholder="请输入价格"
          />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="upload-demo"
            action="#"
            :on-change="handleEditImageChange"
            :show-file-list="false"
            :before-upload="beforeUpload"
            ref="editUploadRef"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <img v-if="editedItem.product_image" :src="editedItem.product_image" alt="商品图片" style="width: 100px; margin-top: 10px;">
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateSavedItem">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElNotification, ElMessageBox } from 'element-plus';

const items = ref([]);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const newItem = ref({
  product_name: '',
  product_description: '',
  product_price: '',
  product_image: ''
});
const editedItem = ref({});
const isLoading = ref(false);
const uploadRef = ref(null);
const editUploadRef = ref(null);

const fetchItems = async () => {
  isLoading.value = true;
  try {
    const userId = localStorage.getItem('userId'); 
    if (!userId) {
      ElNotification({
        title: 'Error',
        message: 'User ID not found in local storage. Please log in again.',
        type: 'error',
      });
      return;
    }
    const response = await axios.get(`http://localhost:3000/items/user/?userId=${userId}`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });
    items.value = response.data;
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: 'Failed to fetch items',
      type: 'error',
    });
    console.error('Error fetching items:', error);
  } finally {
    isLoading.value = false;
  }
};

onMounted(() => {
  fetchItems();
});                                                    

const addItem = () => {
  addDialogVisible.value = true;
};

const saveItem = async () => {
  if (!newItem.value.product_name || !newItem.value.product_price) {
    ElNotification({
      title: '错误',
      message: '请输入商品名称和价格',
      type: 'error',
    });
    return;
  }
  try {
    const userId = localStorage.getItem('userId'); 
    const newItemWithUser = {
      ...newItem.value,
      user_id: userId
    };
    const response = await axios.post('http://localhost:3000/items', newItemWithUser, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });
    await fetchItems();
    addDialogVisible.value = false;
    newItem.value = {
      product_name: '',
      product_description: '',
      product_price: '',
      product_image: ''
    };
    uploadRef.value.clearFiles();
    ElNotification({
      title: 'Success',
      message: '商品添加成功',
      type: 'success',
    });
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: 'Failed to add item',
      type: 'error',
    });
    console.error('Error adding item:', error);
  }
};

const editItem = (item) => {
  editedItem.value = { ...item };
  editDialogVisible.value = true;
};

const updateSavedItem = async () => {
  if (!editedItem.value.product_name?.trim() || !editedItem.value.product_price) {
    ElNotification({
      title: '错误',
      message: '商品名称和价格不能为空',
      type: 'error',
    });
    return;
  }

  try {
    const payload = {
      product_name: editedItem.value.product_name.trim(),
      product_description: editedItem.value.product_description?.trim() || '',
      product_price: Number(editedItem.value.product_price),
      product_image: editedItem.value.product_image
    };

    if (isNaN(payload.product_price) || payload.product_price <= 0) {
      ElNotification({
        title: '错误',
        message: '商品价格必须为有效正数',
        type: 'error',
      });
      return;
    }

    const response = await axios.put(
      `http://localhost:3000/items/${editedItem.value.item_id}`,
      payload,
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json'
        }
      }
    );

    const index = items.value.findIndex(item => item.item_id === editedItem.value.item_id);
    if (index !== -1) {
      items.value[index] = { ...response.data }; 
    }

    editDialogVisible.value = false;
    editUploadRef.value.clearFiles();
    ElNotification({
      title: '成功',
      message: '商品更新成功',
      type: 'success',
    });
  } catch (error) {
    const errorMessage = error.response?.data?.message || error.message || '未知错误';
    ElNotification({
      title: '更新失败',
      message: `错误原因: ${errorMessage}`,
      type: 'error',
      duration: 5000
    });
    console.error('更新错误详情:', {
      request: error.config?.data,
      response: error.response?.data,
      stack: error.stack
    });
  }
};

const confirmDelete = (item) => {
  ElMessageBox.confirm(
    `是否确认删除 ${item.product_name} 商品？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteItem(item.item_id);
  }).catch(() => {
    ElNotification({
      title: '取消',
      message: '已取消删除操作',
      type: 'info'
    });
  });
};

const deleteItem = async (id) => {
  try {
    const token = localStorage.getItem('token');
    const response = await axios.delete(`http://localhost:3000/items/${id}`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    items.value = items.value.filter(item => item.item_id !== id);
    ElNotification({
      title: 'Success',
      message: '商品删除成功',
      type: 'success',
    });
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: 'Failed to delete item',
      type: 'error',
    });
    console.error('Error deleting item:', error);
  }
};

const handleImageChange = async (file) => {
  try {
    const formData = new FormData();
    formData.append('image', file.raw);
    const token = localStorage.getItem('token');
    const response = await axios.post('http://localhost:3000/images/upload', formData, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });
    newItem.value.product_image = response.data.url;
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: '图片上传失败',
      type: 'error',
    });
    console.error('Error uploading image:', error);
  }
};

const handleEditImageChange = async (file) => {
  try {
    const formData = new FormData();
    formData.append('image', file.raw);
    const token = localStorage.getItem('token');
    const response = await axios.post('http://localhost:3000/images/upload', formData, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });
    editedItem.value.product_image = response.data.url;
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: '图片上传失败',
      type: 'error',
    });
    console.error('Error uploading image:', error);
  }
};

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJPG) {
    ElNotification({
      title: 'Error',
      message: '请上传 JPG 或 PNG 格式的图片',
      type: 'error',
    });
  }
  return isJPG;
};
</script>

<style scoped>
.product-management {
  padding: 20px;
}
</style>